<template>
  <table>
    <thead>
      <tr>
        <td>
          <input type="text" placeholder="输入商品名称" name="" id="" v-model.trim="book.bookName">
        </td>
        <td>
          <input type="text" placeholder="输入商品价格" name="" id="" v-model.number="book.price">
        </td>
        <td colspan="3">
          <button @click="addBook" :disabled="book.bookName=='' || book.price==''">添加</button>
        </td>
      </tr>
      <tr>
        <td>id</td>
        <td>商品名称</td>
        <td>商品价格</td>
        <td>商品数量</td>
        <td>操作</td>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(v,i) in bookList" :key="i">
        <td>{{v.id}}</td>
        <td>{{v.name}}</td>
        <td>￥{{v.price}}</td>
        <td>
          <button :disabled="v.number==1" @click="v.number!=1?v.number--:''">-</button>
          {{v.number}}
          <button @click="v.number++">+</button>
        </td>
        <td>
          <button @click="deleteBook(v.id)">移除</button>
        </td>
      </tr>
    </tbody>
    <template v-if="bookList.length==0">
      <tbody>
        <tr>
          <td colspan="5">暂无商品</td>
        </tr>
      </tbody>
    </template>
    <tfoot>
      <tr>
        <td colspan="5" style="color:red;">总价：{{sumprice}}</td>
      </tr>
    </tfoot>
  </table>
</template>

<script setup>
import { reactive } from '@vue/reactivity'
import { computed } from '@vue/runtime-core'
  const bookList = reactive([
    {
      id:1,
      name:'《你的背包》',
      price:100,
      number:1
    },
    {
      id:2,
      name:'《百年孤独》',
      price:159,
      number:2
    },
    {
      id:3,
      name:'《美国往事》',
      price:69,
      number:2
    },
    {
      id:4,
      name:'《那些忧伤的年轻人们》',
      price:39,
      number:1
    }
  ])
  const book = reactive({
    bookName:"",
    price:"",
    number:1
  })
  const sumprice = computed(()=>{
    return `${bookList.reduce((sum,item)=>{
      return sum+item.price*item.number
    },0)}￥`
  })
  const deleteBook = (id)=>{
    let index = bookList.findIndex((item)=>{
      return item.id == id;
    })
    bookList.splice(index,1);
  }
  const addBook = ()=>{
    if(book.bookName=="" || book.price=="")return;
    let id = Math.ceil(Math.random()*100)*Math.ceil(Math.random()*1000);
    bookList.push({
      id:id,
      name:book.bookName,
      price:book.price,
      number:book.number
    })
  }
</script>

<style scoped>
table{
  margin: 0 auto;
}
table,td,tr{
  border: 1px solid gray;
  border-collapse: collapse;
}
thead{
  background-color: rgb(134, 133, 130);
  color: aliceblue;
}
tbody tr:nth-child(2n){
  background-color: antiquewhite;
}
td{
  padding: 10px 20px;
}
</style>
